# -*- coding: utf-8 -*-
# test_pipeline.py
import requests
from deepseek_client import call_deepseek
import json
from requests.exceptions import ChunkedEncodingError

def test_diet_analysis():
    user_input = "中午吃了炸鸡和奶茶，晚上吃了牛肉火锅"

    # 调用 MCP
    mcp_resp = requests.post("http://localhost:8001/mcp", json={"input": user_input})
    mcp_data = mcp_resp.json()
    print("MCP 返回：", mcp_data)

    # 调用 DeepSeek
    reply = call_deepseek(mcp_data["routed_input"])
    print("DeepSeek 回复：", reply)

def test_diet_plan():
    user_input = "我想要一个一周减肥计划，主要食物包括香菇、鸡胸肉和燕麦"
    mcp_resp = requests.post("http://localhost:8001/mcp", json={"input": user_input})
    mcp_data = mcp_resp.json()
    print("MCP 返回：", mcp_data)
    reply = call_deepseek(mcp_data["routed_input"])
    print("DeepSeek 回复：", reply)

def test_effects_inquiry():
    user_input = "香菇吃多了会怎样？"
    mcp_resp = requests.post("http://localhost:8001/mcp", json={"input": user_input})
    mcp_data = mcp_resp.json()
    print("MCP 返回：", mcp_data)
    reply = call_deepseek(mcp_data["routed_input"])
    print("DeepSeek 回复：", reply)

def test_avoid_inquiry():
    user_input = "牛奶和虾能一起吃吗？"
    mcp_resp = requests.post("http://localhost:8001/mcp", json={"input": user_input})
    mcp_data = mcp_resp.json()
    print("MCP 返回：", mcp_data)
    reply = call_deepseek(mcp_data["routed_input"])
    print("DeepSeek 回复：", reply)

def test_stream():
    user_input = "我晚上吃什么比较好呢？ 中午吃了炸鸡和奶茶"
    try:
        resp = requests.post(
            "http://localhost:8001/mcp_stream",
            json={"input": user_input},
            stream=True,
            timeout=None,
        )
        print("Stream start →", resp.status_code)
        meta_printed = False
        for line in resp.iter_lines(decode_unicode=True):
            if not line:
                continue
            # SSE: 可能含 event: xxx
            if line.startswith("event: "):
                current_event = line[7:]
                # 下一行应该是 data:
                continue
            if not line.startswith("data: "):
                continue
            data = line[6:]
            # current_event 默认为 token
            current_event = locals().get("current_event", "token")
            if current_event == "meta":
                try:
                    meta_obj = json.loads(data)
                    pretty_meta = json.dumps(meta_obj, ensure_ascii=False)
                    print("Meta:", pretty_meta)
                except json.JSONDecodeError:
                    print("Meta:", data)
                meta_printed = True
                print("\n--- AI 回复 ---\n", end="")
                continue
            if current_event == "done":
                print("\n✅ Stream done")
                break
            # 其他 token 输出
            print(data, end="", flush=True)
    except ChunkedEncodingError:
        # 服务器已发送完毕但提前关闭连接，可忽略
        print("\n⚠️ 连接提前关闭，已接收全部内容。")
    finally:
        try:
            resp.close()
        except Exception:
            pass

if __name__ == "__main__":
    # test_diet_analysis()
    # test_diet_plan()
    # test_effects_inquiry()
    # test_avoid_inquiry()
    test_stream()